#include "crcconfigdlg.h"

CrcConfigDlg::CrcConfigDlg(CRC_CONTAINER & crc_infos, QWidget *parent)
	: QDialog(parent), _crc_infos(crc_infos)
{
	ui.setupUi(this);

	ui.listWidgetCRCs->addItems(_crc_infos.keys());

	ui.toolButtonAddCRC->setDefaultAction(ui.actionAddCRC);
	ui.toolButtonRemoveCRC->setDefaultAction(ui.actionRemoveCRC);
}

CrcConfigDlg::~CrcConfigDlg()
{

}

void CrcConfigDlg::on_actionAddCRC_triggered()
{
	crc_info new_crc;
	new_crc.bitsize = crc_info::bits16;
	new_crc.crc16.final_xor_value = 0;
	new_crc.crc16.initial_remainder = 0;
	new_crc.crc16.truncated_polynominal = 0;
	new_crc.reflect_input = false;
	new_crc.reflect_remainder = false;
	_crc_infos[QString("new crc")] = new_crc;
	ui.listWidgetCRCs->addItem(QString("new crc"));
	ui.listWidgetCRCs->setCurrentItem(ui.listWidgetCRCs->item(ui.listWidgetCRCs->count()));
}

void CrcConfigDlg::on_actionRemoveCRC_triggered()
{
	_crc_infos.remove(ui.listWidgetCRCs->currentItem()->text());
	ui.listWidgetCRCs->removeItemWidget(ui.listWidgetCRCs->currentItem());
	ui.listWidgetCRCs->setCurrentItem(ui.listWidgetCRCs->item(ui.listWidgetCRCs->count()));
}

void CrcConfigDlg::on_listWidgetCRCs_currentItemChanged( QListWidgetItem * current, QListWidgetItem * previous )
{
	if (!current) return;
	const crc_info & crc = _crc_infos[current->text()];
	ui.comboBoxBits->setCurrentIndex( crc.bitsize == crc_info::bits16 ? 0 : 1);
	if (crc.bitsize == crc_info::bits16)
	{
		ui.lineEditPolynom->setText( QString::number(crc.crc16.truncated_polynominal, 16) );
		ui.lineEditReminder->setText(QString::number(crc.crc16.initial_remainder, 16) );
		ui.lineEditFinalXORValue->setText(QString::number(crc.crc16.final_xor_value, 16) );
	}
	else if (crc.bitsize == crc_info::bits32)
	{
		ui.lineEditPolynom->setText( QString::number(crc.crc32.truncated_polynominal, 16) );
		ui.lineEditReminder->setText(QString::number(crc.crc32.initial_remainder, 16) );
		ui.lineEditFinalXORValue->setText(QString::number(crc.crc32.final_xor_value, 16) );
	}
	ui.checkBoxReflectInput->setCheckState(crc.reflect_input ? Qt::Checked : Qt::Unchecked);
	ui.checkBoxReflectRemainder->setCheckState(crc.reflect_remainder ? Qt::Checked : Qt::Unchecked);
}
